/**
 * @file port_flash_config.h
 * @author your name (you@domain.com)
 * @brief 
 * @version 0.1
 * @date 2025-01-09
 * 
 * Copyright (c) 2025, CorAL. All rights reserved.
 * 
 */

#ifndef __PORT_FLASH_CONFIG_H__
#define __PORT_FLASH_CONFIG_H__

/* ==================== [Includes] ========================================== */

#include "xf_utils.h"
#include "xf_fal.h"
#include "drvs.h"

#ifdef __cplusplus
extern "C" {
#endif

/* ==================== [Defines] =========================================== */

#define INTERNAL_FLASH_NAME                 CONFIG_XF_FAL_DEFAULT_FLASH_DEVICE_NAME

#define INTERNAL_FLASH_SECTOR_SIZE          (4 * 1024)
#define INTERNAL_FLASH_PAGE_SIZE            (256)
#define INTERNAL_FLASH_IO_SIZE              (4)

#define SECTOR_SIZE                         INTERNAL_FLASH_SECTOR_SIZE
#define PAGE_SIZE                           INTERNAL_FLASH_PAGE_SIZE
#define IO_SIZE                             INTERNAL_FLASH_IO_SIZE

#define INTERNAL_FLASH_START_ADDR           (0)
#define INTERNAL_FLASH_LEN                  (CONFIG_PORT_FAL_FLASH_SIZE_KB * 1024)

#define START_ADDR                          INTERNAL_FLASH_START_ADDR

#define USER_PART                           CONFIG_XF_FAL_DEFAULT_PARTITION_NAME

/* OTA 相关 */

/// examples\loader
/* 暂不支持 */
#define CFG_USE_LOAD  0

#ifndef FLASH_BASE
#define FLASH_BASE              (0x18000000)
#endif

/* word len: 以 4 字节为单位的长度 */
#define FLASH_PAGE_SIZE_WLEN    (INTERNAL_FLASH_PAGE_SIZE >> 2)

#define FLASH_INFO_PAGE         (0x00)
#define FLASH_INFO_MAGIC        (FLASH_BASE + 0x00)
#define FLASH_INFO_CODE_LEN     (FLASH_BASE + 0x04)
#define FLASH_INFO_CODE_ADDR    (FLASH_BASE + 0x08)

#define OTA_BANK_A_BASE         (0x18004000)
#if (CFG_USE_LOAD)
#define OTA_BANK_B_BASE         (0x18020100)
#else
#define OTA_BANK_B_BASE         (0x18020000)
#endif
#define OTA_BANK_A              (OTA_BANK_A_BASE - FLASH_BASE)
#define OTA_BANK_B              (OTA_BANK_B_BASE - FLASH_BASE)

#define FLASH_ADDR_INVALID      (0xFFFFFFFF)

// #define OTA_FW_SECTOR_MAX_SIZE  ((FLASH_SIZE - OTA_BANK_B) / INTERNAL_FLASH_SECTOR_SIZE)
// #define OTA_FW_MAX_SIZE         (OTA_FW_SECTOR_MAX_SIZE * INTERNAL_FLASH_SECTOR_SIZE) / 16 // 112K

#define OTA_BANK_A_NAME         "ota_0"
#define OTA_BANK_B_NAME         "ota_1"

/* ==================== [Typedefs] ========================================== */

/* ==================== [Global Prototypes] ================================= */

/* ==================== [Macros] ============================================ */

#if !defined(ALIGN_DOWN)
#define ALIGN_DOWN(addr, align)             ((addr) & ~((align) - 1))
#endif /* ALIGN_DOWN */

#if !defined(ALIGN_UP)
#define ALIGN_UP(addr, align)               (((addr) + (align) - 1) & ~((align) - 1))
#endif /* ALIGN_DOWN */

#if !defined(min)
#define min(x, y)                           (((x) < (y)) ? (x) : (y))
#endif

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif /* __PORT_FLASH_CONFIG_H__ */
